﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Collections;
using System.Reflection;
using UMC.Wiki.Entities;
using UMC.Web;

namespace UMC.Wiki.Activities
{
    class SubjectKeywordActivity : WebActivity
    {

        public override void ProcessActivity(WebRequest request, WebResponse response)
        {

            ulong projectId = UMC.Data.Utility.UInt64Parse(this.AsyncDialog("Project", "auto"), 0);//.Value;

            var form = request.SendValues ?? new UMC.Web.WebMeta();
            var Keyword = (form["Keyword"] as string ?? String.Empty);

            var search = new Subject() { project_id = projectId };

            if (String.IsNullOrEmpty(Keyword) == false)
            {
                search.Title = Keyword;
            }

            var subs = new List<Subject>();
            var ids = new List<ulong>();
            var items = new List<ProjectItem>();

            int nextIndex;
            ;


            var project = DataFactory.Instance().Project(projectId);

            UMC.Data.Utility.Each(DataFactory.Instance().Search(search, 0, out nextIndex, 8), dr =>
             {
                 if (ids.Contains(dr.project_item_id.Value) == false)
                     ids.Add(dr.project_item_id.Value);
                 subs.Add(dr);
             });

            if (ids.Count > 0)
            {
                items.AddRange(DataFactory.Instance().ProjectItem(ids.ToArray()));

            }
            var data = new List<WebMeta>();
            foreach (var c in subs)
            {
                var p = items.Find(i => i.Id == c.project_item_id);
                if (p != null)
                {
                    data.Add(new WebMeta().Put("text", c.Title).Put("path", String.Format("{0}/{1}/{2}", project.Code, p.Code, c.Code)).Put("id", c.Id));
                }
            }
            response.Redirect(data);

        }

    }
}